package leetcode101.tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Synhard
 * @version 1.0
 * @class Code9
 * @description 144. 二叉树的前序遍历
 * 给你二叉树的根节点 root ，返回它节点值的 前序 遍历。
 *
 *
 * 示例 1：
 *
 *
 * 输入：root = [1,null,2,3]
 * 输出：[1,2,3]
 * 示例 2：
 *
 * 输入：root = []
 * 输出：[]
 * 示例 3：
 *
 * 输入：root = [1]
 * 输出：[1]
 * 示例 4：
 *
 *
 * 输入：root = [1,2]
 * 输出：[1,2]
 * 示例 5：
 *
 *
 * 输入：root = [1,null,2]
 * 输出：[1,2]
 *
 * 提示：
 *
 * 树中节点数目在范围 [0, 100] 内
 * -100 <= Node.val <= 100
 *
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-06-23 10:01
 */
public class Code9 {


    public static void main(String[] args) {

    }

    public static List<Integer> preorderTraversal1(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }

    private static void dfs(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        dfs(root.left, res);
        dfs(root.right, res);
    }

//    public static List<Integer> preorderTraversal(TreeNode root) {
//        List<Integer> res = new ArrayList<>();
//        Deque<TreeNode> stack = new LinkedList<>();
//        stack.add(root);
//        while (!stack.isEmpty()) {
//            TreeNode cur = stack.peekFirst();
//            if (cur != null) {
//                stack.removeFirst();
//                if (cur.right != null) stack.addFirst(cur.right);
//                if (cur.left != null) stack.addFirst(cur.left);
//                stack.addFirst(cur);
//                stack.addFirst(null);
//            } else {
//                stack.removeFirst();
//                res.add(stack.removeFirst().val);
//            }
//        }
//        return res;
//    }

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        stack.addFirst(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peekFirst();
            if (cur != null) {
                stack.removeFirst();
                if (cur.right != null) {
                    stack.addFirst(cur.right);
                }
                if (cur.left != null) {
                    stack.addFirst(cur.left);
                }
                stack.addFirst(cur);
                stack.addFirst(null);
            } else {
                stack.removeFirst();
                res.add(stack.removeFirst().val);
            }
        }
        return res;
    }
}
